<template>
  <div class="app-container">
    <div class="top-bar-container">
      <el-row>
        <el-col :span="16">
          <div class="search-container">
            <search-form @search-submit="getActivityList">
              <search-input v-model="listQuery.id" placeholder="ID" />
              <search-input v-model="listQuery.name" placeholder="名称" />
            </search-form>
          </div>
        </el-col>
        <el-col :span="8">
          <el-row type="flex" justify="end">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-plus"
              @click="handleCreateActivity"
            >新增活动
            </el-button>
          </el-row>
        </el-col>
      </el-row>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      stripe
      highlight-current-row
    >
      <el-table-column
        align="center"
        label="名称"
        prop="name"
        fixed
        width="150"
      />

      <el-table-column
        align="center"
        label="活动类型"
        prop="activityType"
        fixed
        width="150"
      >
        <template v-slot="scope">
          {{ activityTypeMap[scope.row.activityType] }}
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        label="活动范围"
        prop="activityScope"
        width="150"
      >
        <template v-slot="scope">
          <div
            v-for="item in scope.row.activityScope"
            :key="item"
            style="margin: 2px"
          >
            <el-tag>
              {{ item | activityScopeFilter }}
            </el-tag>
          </div>
        </template>
      </el-table-column>

      <el-table-column align="center" label="主办单位" prop="organizer" />

      <el-table-column
        align="center"
        label="发布人"
        prop="companyName"
        width="150"
      />

      <el-table-column
        align="center"
        label="活动地点"
        prop="location"
        width="150"
      />

      <el-table-column align="center" label="报名人数" prop="applied" />

      <el-table-column align="center" label="限制人数" prop="limitNum" />

      <el-table-column align="center" label="开始时间" width="150">
        <template v-slot="scope">
          {{ scope.row.startTime | formatDate }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="结束时间" width="150">
        <template v-slot="scope">
          {{ scope.row.endTime | formatDate }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="活动状态" width="100">
        <template v-slot="scope">
          <el-tag
            :type="
              scope.row.status || scope.row.status === 1 ? 'success' : 'danger'
            "
          >
            {{ scope.row.status | enableStatusFilter }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="审核状态" width="150">
        <template v-slot="scope">
          <el-tag :type="scope.row.auditStatus == 10 ? 'success' : 'danger'">
            {{ scope.row.auditStatus | activityAuditStatusFilter }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        label="审核备注"
        prop="auditReason"
        width="150"
      />

      <el-table-column
        align="center"
        label="创建时间"
        prop="createdTime"
        width="160"
      >
        <template v-slot="scope">
          {{ scope.row.createdTime | formatDateTime }}
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        label="更新时间"
        prop="updatedTime"
        width="160"
      >
        <template v-slot="scope">
          {{ scope.row.updatedTime | formatDateTime }}
        </template>
      </el-table-column>

      <el-table-column align="center" fixed="right" label="操作" width="280">
        <template v-slot="scope">
          <el-button-group>
            <el-button
              v-if="scope.row.auditStatus === 10 && scope.row.status === 0"
              type="success"
              size="mini"
              title="开启"
              @click="handleActivityOpen(scope.row.id)"
            >
              开启
            </el-button>

            <el-button
              v-if="scope.row.auditStatus === 10 && scope.row.status === 1"
              type="danger"
              size="mini"
              title="关闭"
              @click="handleActivityClose(scope.row.id)"
            >
              关闭
            </el-button>
            <el-button
              type="primary"
              size="mini"
              title="查看"
              @click="handleViewActivityRow(scope.$index)"
            >
              查看
            </el-button>
            <el-button
              type="warning"
              size="mini"
              title="编辑"
              @click="handleEditActivityRow(scope.$index)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="mini"
              title="删除"
              @click="handleDeleteActivityRow(scope.$index)"
            >
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getActivityList"
    />

    <el-dialog
      :title="editForm.id ? '编辑活动' : '新增活动'"
      :visible.sync="dialogEditVisible"
      width="900px"
      @close="handleEditFormDialogClose"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="editRules"
        class="edit-form"
        autocomplete="on"
      >
        <el-form-item prop="name" label="活动名称" label-width="80px">
          <el-input v-model="editForm.name" />
        </el-form-item>

        <el-form-item prop="organizer" label="主办单位" label-width="80px">
          <el-input v-model="editForm.organizer" />
        </el-form-item>

        <el-form-item prop="location" label="活动地点" label-width="80px">
          <el-input v-model="editForm.location" />
        </el-form-item>

        <el-form-item prop="activityType" label="活动类型" label-width="80px">
          <el-select
            v-model="editForm.activityType"
            placeholder="请选择活动类型"
          >
            <el-option
              v-for="item in activityTypeList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="activityType" label="适用对象" label-width="80px">
          <div style="display: flex; flex-direction: row">
            <el-checkbox
              v-model="checkAll"
              style="margin-right: 30px"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >全选
            </el-checkbox>
            <el-checkbox-group
              v-model="editForm.activityScope"
              @change="handleCheckedScopeChange"
            >
              <el-checkbox
                v-for="item in activityScopeList"
                :key="item.value"
                :label="item.value"
              >
                {{ item.name }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>

        <el-form-item prop="limitNum" label="活动人数" label-width="80px">
          <el-input-number v-model="editForm.limitNum" :min="0" :max="999999" />
        </el-form-item>

        <el-form-item prop="openApply" label="开启报名" label-width="80px">
          <el-switch v-model="editForm.openApply" />
        </el-form-item>

        <el-form-item prop="startTime" label="活动时间" label-width="80px">
          <el-date-picker
            v-model="activityDateTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="onActivityChange"
          />
        </el-form-item>

        <!--        <el-form-item prop="status" label="活动状态" label-width="80px">-->
        <!--          <el-switch v-model="editForm.status" />-->
        <!--        </el-form-item>-->

        <el-form-item label="活动图片" prop="img" label-width="80px">
          <single-upload-image
            v-model="activityImage"
            :data-obj="{ refType: 'activityImg', relativePath: 'activity/img' }"
            file-type="bmp|jpg|gif|jpeg|png"
          />
        </el-form-item>

        <el-form-item
          class="d-flex flex-column"
          prop="description"
          label="活动介绍"
        >
          <Tinymce ref="editor" v-model="editForm.description" :height="400" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSaveActivity">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="查看活动"
      :visible.sync="dialogViewVisible"
      width="900px"
    />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination/index.vue'
import SearchForm from '@/components/SearchForm/index.vue'
import SearchInput from '@/components/SearchForm/SearchInput/index.vue'
import {
  adminActivityClose,
  adminActivityCreate,
  adminActivityDelete,
  adminActivityOpen,
  adminActivitySearch,
  adminActivityUpdate
} from '@/api/rest/activity'
import {
  activityScopeList,
  activityScopeMap,
  yesNoStatusList
} from '@/utils/dict'
import { elRequiredRule } from '@/utils/el-validator'
import { dictConfigItemByDictKeyList } from '@/api/rest/dictconfig'
import { DICT_CONFIG_KEY_ACTIVITY_TYPE } from '@/utils/constant'
import Tinymce from '@/components/Tinymce/index.vue'
import SingleUploadImage from '@/components/Upload/SingleImage.vue'

const initForm = {
  id: null,
  name: null,
  description: null,
  activityType: null,
  activityScope: [],
  organizer: null,
  location: null,
  limitNum: 0,
  openApply: 0,
  startTime: null,
  endTime: null,
  status: 0,
  imageIdList: []
}

export default {
  name: 'ActivityList',
  components: {
    SingleUploadImage,
    Tinymce,
    SearchInput,
    Pagination,
    SearchForm
  },
  data() {
    return {
      imageUrl: process.env.VUE_APP_BASE_API + '/api/admin/file/view/',
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        id: null,
        name: null,
        page: 1,
        limit: 10
      },
      editForm: { ...initForm },
      editRules: {
        name: [elRequiredRule],
        organizer: [elRequiredRule]
      },
      yesNoStatusList: yesNoStatusList,
      activityScopeList: activityScopeList,
      dialogEditVisible: false,
      dialogViewVisible: false,
      activityTypeList: [],
      activityTypeMap: [],
      activityDateTime: [],
      activityImage: 0,
      currentActivity: null,
      checkAll: false,
      isIndeterminate: false
    }
  },
  computed: {
    activityScopeMap() {
      return activityScopeMap
    }
  },
  created() {
    this.getActivityTypeList()
    this.getActivityList()
  },
  methods: {
    getActivityList() {
      this.listLoading = true
      adminActivitySearch(this.listQuery).then((response) => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },

    getActivityTypeList() {
      dictConfigItemByDictKeyList(DICT_CONFIG_KEY_ACTIVITY_TYPE).then(
        (response) => {
          this.activityTypeList = []
          const map = {}
          response.data.forEach((item) => {
            this.activityTypeList.push({
              value: item.itemValue,
              name: item.itemName
            })
            map[item.itemValue] = item.itemName
          })
          this.activityTypeMap = map
        }
      )
    },

    onActivityChange(e) {
      this.editForm.startTime = e[0]
      this.editForm.endTime = e[1]
    },

    handleViewActivityRow(index) {
      this.$router.push({ path: `/activity/view?id=${this.list[index].id}` })
    },

    handleEditActivityRow(index) {
      const _item = { ...this.list[index] }
      if (_item.imageIdList && _item.imageIdList.length > 0) {
        this.activityImage = ~~_item.imageIdList[0]
      } else {
        this.activityImage = 0
      }
      if (_item.startTime && _item.endTime) {
        this.activityDateTime = [_item.startTime, _item.endTime]
      } else {
        this.activityDateTime = []
      }
      if (!_item.activityScope) {
        _item.activityScope = []
        this.isIndeterminate = false
      } else {
        this.isIndeterminate = _item.activityScope.length > 0
      }

      _item.openApply = ~~_item.openApply === 1
      _item.status = ~~_item.status === 1

      this.editForm = { ..._item }
      this.dialogEditVisible = true
    },
    handleDeleteActivityRow(index) {
      const data = this.list[index]
      this.$confirm('此操作将删除活动, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        adminActivityDelete(data.id)
          .then(() => {
            this.$message({
              type: 'success',
              message: '删除活动成功'
            })
            this.getActivityList()
          })
          .catch(() => {})
      })
    },
    handleCreateActivity() {
      this.editForm = { ...initForm }
      this.activityImage = 0
      this.activityDateTime = []
      this.isIndeterminate = false
      this.dialogEditVisible = true
    },
    handleSaveActivity() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.editForm.openApply = this.editForm.openApply ? 1 : 0
          this.editForm.status = this.editForm.status ? 1 : 0

          this.editForm.imageIdList = [this.activityImage]

          if (this.editForm.id) {
            adminActivityUpdate(this.editForm).then((response) => {
              this.$message({
                message: '编辑活动成功',
                type: 'success'
              })
              this.getActivityList()
              this.dialogEditVisible = false
            })
          } else {
            adminActivityCreate(this.editForm).then((response) => {
              this.$message({
                message: '新增活动成功',
                type: 'success'
              })
              this.getActivityList()
              this.dialogEditVisible = false
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleEditFormDialogClose() {
      this.$refs.editForm.clearValidate()
    },
    handleDivisionChange(value) {
      this.editForm.areaCode = value[value.length - 1]
    },
    handleCheckedScopeChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.activityScopeList.length
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.activityScopeList.length
    },
    handleCheckAllChange(value) {
      this.editForm.activityScope = value
        ? this.activityScopeList.map((item) => item.value)
        : []
      this.isIndeterminate = false
    },
    handleActivityOpen(id) {
      this.$confirm('此操作将开启活动, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        adminActivityOpen(id)
          .then(() => {
            this.$message({
              type: 'success',
              message: '开启活动成功'
            })
            this.getActivityList()
          })
          .catch(() => {})
      })
    },
    handleActivityClose(id) {
      this.$confirm('此操作将关闭活动, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        adminActivityClose(id)
          .then(() => {
            this.$message({
              type: 'success',
              message: '关闭活动成功'
            })
            this.getActivityList()
          })
          .catch(() => {})
      })
    }
  }
}
</script>
<style scoped lang="scss">
.flex-column {
  display: flex;
  flex-direction: column;

  ::v-deep .el-form-item__label {
    width: 80px;
  }

  .el-form-item__content {
    margin-left: 0;
  }
}
</style>
